const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const User = require('../models/User.js')
const auth = require('../middleware/auth.js')
const dotenv = require('dotenv')
const { generateVerifyCode, sendVerifyCode } = require('../config/email.js')
const { setVerifyCode, getVerifyCode, deleteVerifyCode } = require('../services/redis.js')

dotenv.config()

const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-123'

// 注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, password, verifyCode } = req.body

    // 验证必填字段
    if (!username || !email || !password || !verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '所有字段都是必填的',
        success: false
      })
    }

    // 验证验证码
    const storedCode = await getVerifyCode(email)
    if (!storedCode || storedCode !== verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '验证码错误或已过期',
        success: false
      })
    }

    // 检查用户是否已存在
    const existingUser = await User.findByUsername(username)
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: '用户已存在',
        success: false
      })
    }
    const existingEmail = await User.findByEmail(email)
    if (existingEmail) {
      return res.status(400).json({
        code: 400,
        message: '邮箱已被注册',
        success: false
      })
    }

    // 创建新用户
    const userId = await User.create({ username, email, password })

    // 删除验证码
    await deleteVerifyCode(email)

    // 生成JWT
    const token = jwt.sign({ userId }, JWT_SECRET, {
      expiresIn: '24h'
    })

    // 获取新创建的用户信息
    const user = await User.findById(userId)
    const { password: _, ...userWithoutPassword } = user

    res.status(201).json({
      code: 201,
      message: '注册成功',
      success: true,
      data: {
        token,
        user: userWithoutPassword
      }
    })
  } catch (err) {
    console.error('注册错误:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body

    if (!username || !password) {
      return res.status(400).json({
        code: 400,
        message: '用户名和密码不能为空',
        success: false
      })
    }

    // 查找用户
    const user = await User.findByUsername(username)
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: '用户名或密码错误',
        success: false
      })
    }

    // 验证密码
    try {
      const isMatch = await User.comparePassword(password, user.password)
      if (!isMatch) {
        return res.status(401).json({
          code: 401,
          message: '用户名或密码错误',
          success: false
        })
      }
    } catch (error) {
      console.error('密码验证错误:', error)
      return res.status(500).json({
        code: 500,
        message: '密码验证失败',
        success: false
      })
    }

    // 生成JWT
    const token = jwt.sign({ userId: user.id }, JWT_SECRET, {
      expiresIn: '24h'
    })

    // 排除密码字段
    const { password: _, ...userWithoutPassword } = user

    // 返回token和用户信息
    res.json({
      code: 200,
      message: '登录成功',
      success: true,
      data: {
        token,
        user: userWithoutPassword
      }
    })
  } catch (err) {
    console.error('登录错误:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 获取用户信息
router.get('/profile', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    // 排除密码字段
    const { password, ...userWithoutPassword } = user
    res.json(userWithoutPassword)
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新用户设置
router.post('/update-settings', auth, async (req, res) => {
  console.log('收到设置更新请求:', {
    body: req.body,
    userId: req.user?.userId
  })

  try {
    const { theme, api_key, model, temperature } = req.body
    await User.updateSettings(req.user.userId, { theme, api_key, model, temperature })

    const user = await User.findById(req.user.userId)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      })
    }

    console.log('设置更新成功:', user)

    res.json({
      code: 200,
      message: '设置更新成功',
      success: true,
      data: {
        theme: user.theme,
        api_key: user.api_key,
        model: user.model,
        temperature: user.temperature
      }
    })
  } catch (err) {
    console.error('更新设置失败:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 发送验证码
router.post('/send-code', async (req, res) => {
  try {
    const { email, type = 'default' } = req.body

    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '邮箱不能为空',
        success: false
      })
    }

    const verifyCode = generateVerifyCode()

    // 可以根据不同的type发送不同内容的邮件
    let emailSubject = '验证码';
    let emailContent = `您的验证码是: ${verifyCode}，有效期10分钟`;

    if (type === 'reset-password') {
      emailSubject = '密码重置验证码';
      emailContent = `您正在进行密码重置操作，验证码是: ${verifyCode}，有效期10分钟。如非本人操作，请忽略此邮件。`;
    }

    const sendResult = await sendVerifyCode(email, verifyCode, emailSubject, emailContent)

    if (!sendResult) {
      return res.status(500).json({
        code: 500,
        message: '验证码发送失败',
        success: false
      })
    }

    // 在Redis中存储验证码时可以加入类型标记
    await setVerifyCode(email, verifyCode, type)

    res.json({
      code: 200,
      message: '验证码已发送',
      success: true
    })
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 更新用户设置 - 新路由
router.put('/profile/settings', auth, async (req, res) => {
  console.log('收到设置更新请求:', {
    body: req.body,
    userId: req.user?.userId
  })

  try {
    const { theme, api_key, model, temperature } = req.body
    await User.updateSettings(req.user.userId, { theme, api_key, model, temperature })

    const user = await User.findById(req.user.userId)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      })
    }

    console.log('设置更新成功:', user)

    res.json({
      code: 200,
      message: '设置更新成功',
      success: true,
      data: {
        theme: user.theme,
        api_key: user.api_key,
        model: user.model,
        temperature: user.temperature
      }
    })
  } catch (err) {
    console.error('更新设置失败:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 更新邮箱
router.put('/update-email', auth, async (req, res) => {
  try {
    const { newEmail, verifyCode } = req.body;
    const userId = req.user.userId;

    // 获取当前用户信息
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      });
    }

    // 检查新邮箱是否与当前邮箱相同
    if (user.email === newEmail) {
      return res.status(400).json({
        code: 400,
        message: '新邮箱与当前邮箱相同，无需更改',
        success: false
      });
    }

    // 验证必填字段
    if (!newEmail || !verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '邮箱和验证码不能为空',
        success: false
      });
    }

    // 验证验证码
    const storedCode = await getVerifyCode(newEmail);
    if (!storedCode || storedCode !== verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '验证码错误或已过期',
        success: false
      });
    }

    // 检查新邮箱是否已被其他用户使用
    const existingUser = await User.findByEmail(newEmail);
    if (existingUser && existingUser.id !== userId) {
      return res.status(400).json({
        code: 400,
        message: '该邮箱已被其他用户注册',
        success: false
      });
    }

    // 更新邮箱
    const updated = await User.updateEmail(userId, newEmail);
    if (!updated) {
      return res.status(500).json({
        code: 500,
        message: '邮箱更新失败',
        success: false
      });
    }

    // 删除验证码
    await deleteVerifyCode(newEmail);

    // 获取更新后的用户信息
    const updatedUser = await User.findById(userId);
    const { password: _, ...userWithoutPassword } = updatedUser;

    res.json({
      code: 200,
      message: '邮箱更新成功',
      success: true,
      data: {
        user: userWithoutPassword
      }
    });
  } catch (err) {
    console.error('更新邮箱错误:', err);
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    });
  }
});

// 修改密码路由
router.put('/update-password', auth, async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;
    const userId = req.user.userId;

    console.log('密码更新请求:', {
      userId,
      hasOldPassword: !!oldPassword,
      hasNewPassword: !!newPassword
    });

    const user = await User.findById(userId);
    console.log('查询到的用户信息:', {
      found: !!user,
      hasPasswordHash: !!user?.password,
      userId: user?.id,
      fields: user ? Object.keys(user) : []
    });

    // 验证参数
    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        code: 400,
        message: '旧密码和新密码不能为空',
        success: false
      });
    }

    // 查找用户并确保用户存在
    const userExists = await User.findById(userId);
    if (!userExists) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      });
    }

    // 确保用户有密码哈希
    if (!userExists.password) {
      return res.status(400).json({
        code: 400,
        message: '用户账户状态异常，无法更新密码',
        success: false
      });
    }

    // 验证旧密码
    try {
      const isMatch = await User.comparePassword(oldPassword, userExists.password);
      if (!isMatch) {
        return res.status(400).json({
          code: 400,
          message: '旧密码不正确',
          success: false
        });
      }
    } catch (error) {
      console.error('验证旧密码出错:', error);
      return res.status(500).json({
        code: 500,
        message: '密码验证失败: ' + error.message,
        success: false
      });
    }

    // 更新密码
    await User.updatePassword(userId, newPassword);

    res.json({
      code: 200,
      message: '密码更新成功',
      success: true
    });
  } catch (err) {
    console.error('更新密码错误:', err);
    res.status(500).json({
      code: 500,
      message: err.message || '更新密码失败',
      success: false
    });
  }
});

// 通过验证码重置密码
router.post('/reset-password', async (req, res) => {
  try {
    const { email, verifyCode, newPassword } = req.body;

    // 验证必填字段
    if (!email || !verifyCode || !newPassword) {
      return res.status(400).json({
        code: 400,
        message: '邮箱、验证码和新密码不能为空',
        success: false
      });
    }

    // 验证用户是否存在
    const user = await User.findByEmail(email);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      });
    }

    // 验证验证码
    const storedCode = await getVerifyCode(email, 'reset-password');
    if (!storedCode || storedCode !== verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '验证码错误或已过期',
        success: false
      });
    }

    // 重置密码
    const updated = await User.updatePassword(user.id, newPassword);
    if (!updated) {
      return res.status(500).json({
        code: 500,
        message: '密码重置失败',
        success: false
      });
    }

    // 删除验证码
    await deleteVerifyCode(email);

    res.json({
      code: 200,
      message: '密码重置成功',
      success: true
    });
  } catch (err) {
    console.error('重置密码错误:', err);
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    });
  }
});

module.exports = router
